//
//  CXComposeView.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/1/25.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
import pop

class CXComposeView: UIView {
    
    /// 保存父控制器
    var target: UIViewController?
    
    ///  呼叫父控制器执行block
   // var help: (()-> Void)?
    /// 懒加载
    private lazy var buttonInfos: [CXComposeModel] = {
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        let infolist = NSArray(contentsOfFile: path!)
        
        var tmpArry = [CXComposeModel]()
        for info in infolist! {
            tmpArry.append(CXComposeModel(dict: info as! [String : AnyObject]))
        }
        return tmpArry
    }()
    //存放自定义按钮
    private lazy var aniButtons = [CXComposeButton]()
    //标语
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    //模糊背景图片
    private lazy var bgBlurView: UIImageView = UIImageView(image: UIImage.getScreenImage().applyLightEffect()) //还要进行模糊处理
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        addButtons()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func getParentController(target: UIViewController) {
        
        self.target = target
        //解决看不到控制器的弹出动画问题
        target.view.addSubview(self)
        //这样的话 就不必在target点击操作里面，在window上添加当前view了
    }
    //在window改变以后进行的操作.该方法在控件添加到父控件以及从后者移走都会调用。
    //而 didMoveToSuperview方法只会在添加时调用。
    override func didMoveToWindow() {
        
        for (index, button) in aniButtons.enumerate() {
            addAnimationToButton(index, button: button)
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        //点击后 按钮一个接一个做动画；消失
        for (index, button) in aniButtons.reverse().enumerate() {
            addAnimationToButton(index, isUP: false, button: button)
        }
        //延迟指定时间后 将当前view撤走
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.5 * CGFloat(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
    }
}
// MARK: - 每个按钮的移动动画
extension CXComposeView {
    
    private func addAnimationToButton(index:Int, isUP:Bool = true, button: CXComposeButton) {
        
        //在这里使用 FaceBook 提供的一个动画框架;
        let animator = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //通过改变中心坐标来直接改变位置
        animator.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y + (isUP ? -330 : 330)))
        animator.springSpeed = 10
        animator.springBounciness = 8
        //让按钮一个接一个动画
        animator.beginTime = CACurrentMediaTime() + Double(index) * 0.025 //从代码开始执行的当前时间开始
        button.pop_addAnimation(animator, forKey: nil)
    }
    ///  按钮点击的动画
    @objc private func btnClick(button: CXComposeButton) {
        
      UIView.animateWithDuration(0.25, animations: { () -> Void in
        
        for cbutton in self.aniButtons {
            if cbutton == button {
                cbutton.transform = CGAffineTransformMakeScale(2.0, 2.0)
            } else {
                cbutton.transform = CGAffineTransformMakeScale(0.5, 0.5)
            }
            cbutton.alpha = 0
        }
        }) { (_) -> Void in
            //completed
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                for cbutton in self.aniButtons {
                    cbutton.transform = CGAffineTransformIdentity
                    cbutton.alpha = 1
                }
            })//这个UIView的类方法是一个同步方法
            //TODO: 点击了文字按钮之后 弹出带导航栏的控制器
            guard let btnInfo = button.buttonInfo else {
                return
            }
            print(NSStringFromClass(CXComposeController.self))
            let cls = NSClassFromString(btnInfo.className!) as! CXComposeController.Type
            let vc = cls.init()
            self.target?.presentViewController(CXNavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                self.removeFromSuperview()
                
            })
        }
    }
    

}
// MARK: - 布置UI等操作
extension CXComposeView {
    
    private func setupUI() {
        
        //设置尺寸
        frame.size = CGSize(width: SCREENW, height: SCREENH) //origin默认为 CGPointZero
        
        addSubview(bgBlurView)
        addSubview(sloganView)
        
        bgBlurView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        sloganView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
    }
    private func addButtons() {
        
        let count = buttonInfos.count
        //设置一下每一个按钮的宽高，按钮之间的间距
        let btnW: CGFloat = 80
        let btnH: CGFloat = 110
        let btnMargin: CGFloat = (SCREENW - btnW * 3) / 4
        
        for i in 0..<count {
            
            let buttonInfo = buttonInfos[i]
            let button = CXComposeButton()
            button.buttonInfo = buttonInfo
//            button.setTitle(buttonInfo.title, forState: .Normal)
//            button.setImage(UIImage(named: buttonInfo.icon!), forState: .Normal)
            
            let col = i % 3
            let row = i / 3
            //设置button的frame
            button.frame.origin = CGPoint(x: CGFloat(col) * (btnW + btnMargin) + btnMargin, y: CGFloat(row) * (btnH + btnMargin) + SCREENH)
            button.frame.size = CGSize(width: btnW, height: btnH)
            //将按钮缓存
            aniButtons.append(button)
            addSubview(button)
            //TODO: 给按钮添加点击事件
            button.addTarget(self, action: "btnClick:", forControlEvents: .TouchUpInside)
        }
        
    }
}